#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from pathlib import Path
import git


class GitTransfer(object):
    def __init__(self, repo_path, old_url, new_url):
        # self.repo = None
        self.repo_path = repo_path
        self.old_url = old_url
        self.new_url = new_url
        self.init_repo()

    def init_repo(self):
        path_obj = Path(self.repo_path)
        if not path_obj.exists():
            repo_obj = git.Repo.clone_from(self.old_url, to_path=self.repo_path)
        else:
            repo_obj = git.Repo(self.repo_path)
        self.repo = repo_obj

    def get_local_branches(self):
        branch_name_list = []
        for i in self.repo.branches:
            branch_name_list.append(i.__str__())

        return branch_name_list

    def get_remote_branches(self):
        return self.repo.remote().refs

    def get_local_need_rsync_branches(self):
        return [item.remote_head for item in self.get_remote_branches() if
                item.remote_head not in ["HEAD", ] + self.get_local_branches()]

    def fetch_remote_branches(self, branches):
        if len(branches) == 0:
            return
        for branch in branches:
            self.repo.remote().fetch("%s:%s" % (branch, branch))

    def add_remote(self, name, url):
        self.repo.create_remote(name, url)

    def check_remote(self, name, url):
        for remote in self.repo.remotes:
            if remote.name == name or remote.url == url:
                return False

        return True
